package cn.genmer.test.security.rpc;

import cn.genmer.test.security.rpc.v2.rpc.protocol.GContent;
import io.netty.buffer.ByteBuf;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerialUtil {
    static ByteArrayOutputStream out = new ByteArrayOutputStream();
    public synchronized static byte[] serialObject(Object obj){
        out.reset();
        ObjectOutputStream oout = null;
        byte[] bytes = null;
       try {
           oout = new ObjectOutputStream(out);
           oout.writeObject(obj);
           bytes = out.toByteArray();
       } catch (Exception e){
           e.printStackTrace();
       }
        return bytes;
    }

    public static GContent parseGContent(ByteBuf content){
        GContent gContent = null;
        byte[] bytes = null;
        try {
            byte[] data = new byte[content.readableBytes()];
            content.readBytes(data);
            ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(data));
            gContent = (GContent) oin.readObject();
        } catch (Exception e){
            e.printStackTrace();
        }
        return gContent;
    }
}
